/**
 * 
 */
package com.alipay.sdk.auth.demo;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.alipay.sdk.auth.APAuthInfo;
import com.alipay.sdk.auth.AlipaySDK;
import com.alipay.sdk.pay.demo.R;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auth_layout);
        
        
        Log.e("MainActivity", "----------- onCreate");


        final SharedPreferences sp = getSharedPreferences("auth_info", Context.MODE_PRIVATE);

        final EditText appId = (EditText) findViewById(R.id.appId);
        final EditText productId = (EditText) findViewById(R.id.productId);
        final EditText pid = (EditText) findViewById(R.id.pid);
        // final EditText redirectUri = (EditText)
        // findViewById(R.id.redirectUri);
        if (sp.getBoolean("hasData", false)) {
            appId.setText(sp.getString("appId", ""));
            productId.setText(sp.getString("productId", ""));
            pid.setText(sp.getString("pid", ""));
            // redirectUri.setText(sp.getString("redirectUri", ""));
        }

        View submit = findViewById(R.id.submit);
        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                startAuth(sp, appId, productId, pid);
            }

        });
    }

    private void startAuth(final SharedPreferences sp, final EditText appId, final EditText productId,
            final EditText pId) {
        String appid = appId.getText().toString();
        String productid = productId.getText().toString();
        String pid = pId.getText().toString();
        String redirecturi = "authresult://com.android.auth.callback:80";

        sp.edit().putBoolean("hasData", true).putString("appId", appid).putString("productId", productid)
                .putString("pid", pid).putString("redirectUri", redirecturi).commit();

        APAuthInfo authInfo = new APAuthInfo(appid, productid, redirecturi, pid);
        AlipaySDK.auth(this, authInfo);
    }
}
